<template>
  <div class="list_container flex both-100">
    <Breadcrumb :title="pageTitle" />
    <div class="content_container">
      <!-- 搜索模块 -->
      <el-form ref="searchMap" :inline="true" :model="searchMap" class="serach_wrapper flex-space-between">
        <div class="search">
          <el-form-item prop="deptName" size="small">
            <el-input v-model="searchMap.deptName" placeholder="部门名称"></el-input>
          </el-form-item>
          <el-form-item prop="status" style="width: 220px" size="small">
            <el-select v-model="searchMap.status" placeholder="字典状态" clearable style="width: 240px">
              <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item class="flex">
            <el-button @click="handleSearch" class="btn_primary">查询</el-button>
            <el-button @click="handleReset" class="btn_cancel">重置</el-button>
          </el-form-item>
        </div>
        <div class="edit">
          <el-form-item class="flex">
            <el-button @click="handleAdd()" class="btn_primary" icon="el-icon-plus">
              新增
            </el-button>
          </el-form-item>
        </div>
      </el-form>
      <!-- 搜索模块over -->

      <!-- 表格模块 -->
      <div class="table_container">
        <el-table v-loading="loading" :data="deptList" row-key="deptId" :default-expand-all="isExpandAll" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column prop="deptName" label="部门名称"></el-table-column>
          <el-table-column prop="orderNum" label="排序"></el-table-column>
          <el-table-column prop="status" label="状态">
            <!-- <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
            </template> -->
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="200">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <div class="button-group">
                <span type="text" class="tag_primary" size="small" @click="handleEdit(scope.row)">编辑</span>
                <span type="text" class="tag_warning" size="small" @click="handleDelete(scope.row)">删除</span>
              </div>

            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加或修改部门对话框 -->
      <el-dialog :title="title" :visible.sync="dialogVisibleDept" append-to-body :close-on-click-modal="false">
        <el-form ref="form" :model="formModel" :rules="rules" label-width="80px" size="small">
          <el-row>
            <el-col :span="24" v-if="formModel.parentId !== 0">
              <el-form-item label="上级部门" prop="parentId">
                <treeselect v-model="formModel.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级部门" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="部门名称" prop="deptName">
                <el-input v-model="formModel.deptName" placeholder="请输入部门名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="显示排序" prop="orderNum">
                <el-input-number v-model="formModel.orderNum" controls-position="right" :min="0" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="负责人" prop="leader">
                <el-input v-model="formModel.leader" placeholder="请输入负责人" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="formModel.phone" placeholder="请输入联系电话" maxlength="11" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="formModel.email" placeholder="请输入邮箱" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门状态">
                <!-- <el-radio-group v-model="formModel.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{dict.label}}</el-radio>
              </el-radio-group> -->
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleDept = false" class="btn_cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm" class="btn_primary">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api";
import { handleTree } from '@/utils/ruoyi'
export default {
  name: 'dept',
  dicts: ['sys_normal_disable'],
  data () {
    return {
      // 加载状态
      loading: false,
      //搜索条件
      searchMap: {
        deptName: undefined,
        status: undefined
      },
      //搜索条件
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 总条数
      total: 0,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 弹框状态 
      dialogVisibleDept: false,
      // 弹框标题
      title: '',
      // 表单数据
      formModel: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级部门不能为空", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  computed: {
    pageTitle () {
      return '部门管理'
    }
  },
  created () {
    this.getList()
  },
  mounted () {

  },
  watch: {},
  methods: {
    /** 查询部门列表 */
    getList () {
      this.loading = true;
      listDept(this.searchMap).then(response => {
        this.deptList = handleTree(response.data, "deptId");
        this.loading = false;
      });
    },
    /** 转换部门数据结构 */
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    /** 新增按钮操作 */
    handleAdd (row) {
      this.reset();
      if (row != undefined) {
        this.formModel.parentId = row.deptId;
      }
      this.dialogVisibleDept = true;
      this.title = "添加部门";
      listDept().then(response => {
        this.deptOptions = handleTree(response.data, "deptId");
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll () {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleEdit (row) {
      this.reset();
      getDept(row.deptId).then(res => {
        this.formModel = res.data;
        this.dialogVisibleDept = true;
        this.title = "修改部门";
        listDeptExcludeChild(row.deptId).then(res => {
          this.deptOptions = handleTree(res.data, "deptId");
          if (this.deptOptions.length == 0) {
            const noResultsOptions = { deptId: this.formModel.parentId, deptName: this.formModel.parentName, children: [] };
            this.deptOptions.push(noResultsOptions);
          }
        });
      });
    },

    handleSearch () {
      this.getList()
    },
    handleReset () {
      this.$refs['searchMap'].resetFields();
      this.handleSearch()
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formModel.deptId != undefined) {
            updateDept(this.formModel).then(res => {
              if (200 === res.code) {
                this.$message.success("修改成功");
                this.dialogVisibleDept = false;
                this.getList();
              }
            });
          } else {
            addDept(this.formModel).then(res => {
              if (200 === res.code) {
                this.$message.success("新增成功");
                this.dialogVisibleDept = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      this.$confirm('是否确认删除名称为"' + row.deptName + '"的数据项？').then(function () {
        return delDept(row.deptId);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      })
    },
    // 表单重置
    reset () {
      this.formModel = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0"
      };
      // this.resetForm("form");
    },
  },
  components: {},
}
</script>

<style lang='less' scoped>
</style>